<template>
    <yh-dialog :visible.sync="visibleTemp" v-bind="$attrs" title="预览查询" :close-on-click-modal="false" width="1400px" @close="handleCloseDialog">
        <div class="dialog-main">
            <el-row>
                <el-col class="sticky" :span="5" style="padding: 10px; padding-right: 0">
                    <el-input v-model="keyword" size="mini" style="width: 100%">
                        <i slot="suffix" class="el-input__icon el-icon-search" @click="search"></i>
                    </el-input>
                    <div class="title">目录</div>
                    <ul>
                        <li :class="{ current: currentKey === 'full' }" @click="handleFileClick('full')">
                            全部
                            <i class="el-icon-download" style="float: right" @click.prevent="downLoad(i.fileNo)">打包下载全部文档</i>
                        </li>
                        <li v-for="i in files" :key="i.fileNo" :class="{ current: currentKey === i.fileNo }" @click="handleFileClick(i.fileNo)">
                            {{ i.name }}
                            <i class="el-icon-download" style="float: right" @click.prevent="downLoad(i.fileNo)">下载</i>
                        </li>
                    </ul>
                </el-col>
                <el-col :span="19" style="min-width: 1040px; min-height: 300px" :key="officeKey">
                    <div v-for="(value, key) in docxObj" :key="key" :name="key">
                        <!-- :style="{
                                display: 'no' + currentKey === key ? '' : 'none',
                            }" -->
                        <VueOfficePdf v-if="pdfNos.includes(key)" :src="value" @rendered="rendered" @error="errorHandler" />
                        <VueOfficeDocx v-else :src="value" @rendered="rendered" @error="errorHandler" />
                    </div>
                </el-col>
                <!-- <el-col class="sticky" :span="3" style="padding: 0 10px">
                    <div style="padding: 5px 0">
                        <el-input
                            v-model="searchValue"
                            prefix-icon="el-icon-search"
                            placeholder="请输入"
                            size="mini"
                            @change="handleSearch"
                        ></el-input>
                    </div>
                    <span style="float: right; padding: 5px">匹配到{{ length }}项</span>

                    <el-button size="mini" type="primary" style="float: right" @click="next">下一个</el-button>
                </el-col> -->
            </el-row>
        </div>

        <div slot="footer" class="dialog-footer" style="text-align: right; padding-right: 10px">
            <el-button size="mini" @click="handleCloseDialog">关闭</el-button>
        </div>
    </yh-dialog>
</template>
<script lang="ts">
import { Component, Prop, PropSync, Vue, Watch } from 'vue-property-decorator';
import VueOfficePdf from '@vue-office/pdf';
import VueOfficeDocx from '@vue-office/docx';
import '@vue-office/docx/lib/index.css';
import { downloadBlob } from '@/utils/request';

@Component({ name: 'SourceOffice', components: { VueOfficePdf, VueOfficeDocx } })
export default class SourceOffice extends Vue {
    @PropSync('visible') syncVisible: boolean;
    @Prop() type: string;
    details: any[] = [
        {
            attachmentFileNos: '[{"name":"禅道统计工具系统运维.pdf","fileNo":517,"uid":1705402243119,"status":"success"}]',
        },
        {
            attachmentFileNos: '[{"name":"关于设立“日增利1号”之合规意见书_2023版(生效).docx","fileNo":515,"uid":1705402243119,"status":"success"}]',
        },
        {
            attachmentFileNos: '[{"name":"关于设立“日增利2号”之合规意见书_2023版(生效).pdf","fileNo":510,"uid":1705402243119,"status":"success"}]',
        },
        {
            attachmentFileNos: '[{"name":"制度文档1_2022版(生效).docx","fileNo":511,"uid":1705402243119,"status":"success"}]',
        },
        {
            attachmentFileNos: '[{"name":"制度文档2_2023版(废弃).docx","fileNo":512,"uid":1705402243119,"status":"success"}]',
        },
        {
            attachmentFileNos: '[{"name":"关于设立“日增利1号”之合规意见书_2023版(生效).docx","fileNo":515,"uid":1705402243119,"status":"success"}]',
        },
        {
            attachmentFileNos: '[{"name":"关于设立“日增利2号”之合规意见书_2023版(生效).pdf","fileNo":510,"uid":1705402243119,"status":"success"}]',
        },
        {
            attachmentFileNos:
                '[{"name":"制度文档1_2022版(生效)制度文档1_2022版(生效)制度文档1_2022版(生效)制度文档1_2022版(生效)制度文档1_2022版(生效).docx","fileNo":511,"uid":1705402243119,"status":"success"}]',
        },
    ];

    public visibleTemp: boolean = false;
    keyword: string = '';
    searchValue: string = '';
    length: number = 0;

    files: any[] = [];
    fileNos: number[] = [];
    currentKey: number | string = ''; // 当前选择目录

    docx = 'http://static.shanhuxueyuan.com/test6.docx'; // 设置文档地址
    docxObj: any = {};
    officeKey: number = 0;
    nextNum: number = -1;
    pdfNos: any[] = [];

    mounted() {}

    @Watch('visible', { immediate: true, deep: true })
    onWatchVisible(value) {
        if (value !== this.visibleTemp) {
            this.visibleTemp = value;

            if (value) {
                this.getFiles();
            }
        }
    }
    // 左侧树查询
    search() {}

    // 左侧点击下载文件
    downLoad(fileNo: string) {
        if (fileNo == 'full') {
            // 全部文件下载
        } else {
            // 单个文件下载
        }
    }

    getFiles() {
        console.log(this.details, 'this.details');

        let files = [];
        let fileNos = [];

        this.details.forEach(element => {
            if (element.attachmentFileNos) {
                files = [...files, ...this.filterNameSuffix(element.attachmentFileNos)];
                fileNos = [...fileNos, ...this.filterNameSuffix(element.attachmentFileNos).map(i => i.fileNo)];
            }
        });

        this.files = files;
        this.currentKey = fileNos[0];
        console.log(fileNos, 'fileNos');

        this.downloadFiles(fileNos);
    }

    async downloadFiles(fileNos) {
        for (let no of fileNos) {
            await downloadBlob({
                url: '/system/download/file/' + no,
                method: 'get',
            }).then(res => {
                console.log(`一个一个下载${no}`);
                this.docxObj['no' + no] = res;
                this.officeKey++;
            });
        }
    }

    /**
     * 过滤不支持的文件后缀
     */
    filterNameSuffix(item) {
        let data = JSON.parse(item);
        this.pdfNos = [...this.pdfNos, ...data.filter(i => i.name.indexOf('.pdf') > -1).map(i => 'no' + i.fileNo)];

        return data.filter(i => i.name.indexOf('.docx') > -1 || i.name.indexOf('.pdf') > -1);
    }

    rendered() {
        console.log('渲染完成');
    }

    errorHandler(e) {
        console.log('渲染失败');
        console.log(e, '???');
    }

    handleSearch(prevContent): void {
        if (prevContent && prevContent.trim()) {
            const spans = document.querySelectorAll('mark:where([class*="yellow-text"])');
            // 去除span标签，只保留文本
            spans.forEach(span => {
                const text = span.textContent;
                span.replaceWith(text);
            });

            // console.log(document.querySelector('.docx-wrapper'), 'querySelector');
            // console.log(document.querySelectorAll('.docx-wrapper'), 'querySelectorAll');

            let keyword = prevContent;
            let doms = document.querySelectorAll('.docx-wrapper');
            let pattern = new RegExp(keyword, 'gi');

            doms.forEach(element => {
                let html = element.innerHTML;
                let newHtml = html.replace(pattern, "<mark style='font-size: inherit' class='yellow-text'>" + keyword + '</mark>');
                element.innerHTML = newHtml;
            });

            const texts = document.querySelectorAll('.yellow-text');
            this.length = texts.length;
            this.nextNum = -1;
            // this.handleFileClick('no' + this.fileNos[0]);
        }
    }

    // changeHandle(event) {
    //     let file = event.target.files[0];
    //     let fileReader = new FileReader();
    //     fileReader.readAsArrayBuffer(file);
    //     fileReader.onload = () => {
    //         this.src = fileReader.result;
    //     };
    // }

    /**
     * 切换目录
     */
    handleFileClick(fileNo): void {
        this.currentKey = fileNo;
        // 滚动条回到顶部
        // document.querySelector('.el-dialog__body').scrollTop = 0;

        document.querySelector(`div:where([name*="${'no' + fileNo}"])`).scrollIntoView({ block: 'start' });
    }

    /**
     * 下一个
     */
    next() {
        let data = [];
        for (const key in this.docxObj) {
            // 获取每个word匹配到的长度
            const doc = document.querySelector(`div:where([name*="${key}"])`);
            data.push({
                fileNo: key,
                has: doc.querySelectorAll('.yellow-text').length,
            });
        }
        // 获取num阈值 超过就换word
        for (let i = 0; i < data.length; i++) {
            if (i > 0) {
                const prevNum = data[i - 1].num;
                const currentLength = data[i].has;
                data[i].num = prevNum + currentLength;
            } else {
                data[i].num = data[i].has;
            }
        }

        console.log(data, 'has');

        console.log(`当前tab: ${this.currentKey}`);

        this.nextNum++;

        console.log(`当前第几项: ${this.nextNum}`);

        // 如果当前word已经看完了 切换到下一个word
        for (let i = 0; i < data.length; i++) {
            const o = data[i];
            if (o.fileNo === 'no' + this.currentKey && this.nextNum > o.num - 1) {
                console.log('该下个word了!');

                // 寻找下一个匹配的tab
                const nextTabs = data.filter(i => i.fileNo !== 'no' + this.currentKey && i.num !== 0);

                if (nextTabs.length) {
                    this.currentKey = Number(nextTabs[0].fileNo.replace('no', ''));
                }
                break;
            }
        }

        const texts = document.querySelectorAll('.yellow-text');
        // 查看了一圈 重置继续循环
        if (this.nextNum >= texts.length) {
            this.nextNum = 0;
        }

        texts[this.nextNum].scrollIntoView({ block: 'center' });
    }

    getRanges(arr) {
        let ranges = [];
        let start = 0;
        let end = 0;

        for (let i = 0; i < arr.length; i++) {
            if (i > 0 && arr[i] != arr[i - 1]) {
                ranges.push([start, end]);
                start = i;
                end = i;
            } else {
                end = Math.max(end, i);
            }
        }

        ranges.push([start, end]);
        return ranges;
    }
    /**
     * 关闭dialog事件
     */
    handleCloseDialog(): void {
        this.syncVisible = false;
    }
}
</script>
<style lang="scss" scoped>
.dialog-main {
    .title {
        font-weight: bold;
        font-size: 13px;
        padding: 5px 0;
    }

    .sticky {
        position: sticky;
        top: 0;
    }

    ul {
        height: calc(65vh - 80px);
        padding-right: 10px;
        overflow: auto;
        li {
            font-size: 12px;
            // overflow: hidden;
            // text-overflow: ellipsis;
            white-space: pre-wrap;
            padding: 10px 0 10px 5px;
            cursor: pointer;
            font-weight: bolder;
        }

        li:hover {
            background: #f9f9f9;
        }

        .current {
            background: #fef7eb !important;
            color: var(--primary);
            // color: #f39603;
            font-weight: bold;
        }
    }
}

/deep/ .el-dialog {
    .el-dialog__header {
        background: #f9f9f9;

        .el-dialog__title,
        .el-dialog__headerbtn .el-dialog__close {
            color: #333333;
        }
    }

    .el-dialog__body {
        max-height: 65vh;
        padding: 0;

        .el-form-item__label {
            height: 25px;
            line-height: 30px;
            /* vertical-align: bottom; */
            overflow: visible;
            padding: 0;
            font-size: 12px;
        }
    }

    .el-dialog__footer {
        text-align: right;
        border-top: none;
        .el-button {
            min-width: 50px;
            border-radius: 4px;
        }
        .el-button + .el-button {
            margin-left: 10px;
        }

        .dialog-footer {
            padding: 0 10px;
        }
    }
}

/deep/ .el-divider--horizontal {
    margin: 0 0 20px 0;
}
</style>
